<template>
  <div id="login">
    <div class="card">
      <van-form @submit="onSubmit" validate-trigger="onSubmit">
        <div class="confirm-btn">
          <span class='login_title'>
            手机号码登录
          </span>
        </div>
        <van-cell-group style="margin-top: 30px;" inset label-width="30px">
          <van-field class="selfInput" v-model="phone" name="phone" placeholder="手机号" type="number" clearable
            :maxlength="11" :rules="[{ pattern, message: '请填写正确的手机号' }]" :clear-icon="'clear'">
            <template #left-icon>
              <div style="display: flex;justify-content: flex-start;">
                <input class='selfCity' readonly v-model="fieldValue" @click="showPicker = true"></input>
                <van-icon name="arrow-down" />
              </div>
              <van-popup v-model:show="showPicker" round position="bottom">
                <van-picker :columns="columns" @cancel="showPicker = false" @confirm="onConfirm" />
              </van-popup>
            </template>
          </van-field>
          <van-field class="selfInput" v-model="code" name='verifyCode' center type="number" label=""
            placeholder="请输入验证码" :rules="[{ required: true, message: '请输入验证码' }]">
            <template #button>
              <span class="_primary" v-if="isWait" @click="getSmsCode">获取验证码</span>
              <van-count-down style="color: #209EE4;width:80px;" ref="countDown" :time="time" @finish="onFinish"
                v-show="!isWait" format="ss">
                <template #default="timeData">
                  <span class="countDownTimes">{{ timeData.seconds }}S</span>
                </template>
              </van-count-down>
            </template>
          </van-field>
        </van-cell-group>
        <div class="confirm-btn" style="margin-top: 30px;margin-bottom: 15px;width:90%;">
          <van-button block type="primary" native-type="submit" :disabled="!phone || !code">
            登录
          </van-button>
        </div>
        <div class="confirm-btn" style="text-align: center;">
          <span class="tips">未注册的手机号验证后将自动创建账号</span>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { CountDown } from 'vant';
import { useStore } from '../store';
import { useRouter } from 'vue-router';

import apis from '../api/index';
import { showToast } from 'vant';

const phone = ref<number | string>();
const code = ref<number>();
const time = ref<number>(60 * 1000);
const isWait = ref<boolean>(true);
const countDown = ref<typeof CountDown>();
const pattern = /^1(3[0-9]|4[5-9]|5[0-35-9]|6[5-6]|7[0-8]|8[0-9]|9[1-35-9])\d{8}$/;
const store = useStore();
const router = useRouter();
const { userLogin, getVerification } = apis;

const columns = [
  { text: '中国+86', value: '+86' },
  { text: '新加坡+65', value: '+65' },
];
const fieldValue = ref('+86');
const showPicker = ref(false);

const onConfirm = ({ selectedOptions }) => {
  showPicker.value = false;
  fieldValue.value = selectedOptions[0].value;
};


const onFinish = () => {
  countDown.value?.reset();
  isWait.value = true;
};
const getSmsCode = async () => {
  let ChinaPhone = /^1[345789]\d{9}$/;
  let SingaporePhone = /^[13689]\d{6,7}$/;
  if (phone.value == '') {
    showToast("手机号不能为空！");
    return;
  } else if (fieldValue.value == '+86') {
    //验证中国手机
    if (ChinaPhone.test(phone.value)) {
    } else {
      showToast("国内手机号格式不正确！")
      return;
    }
  } else if (fieldValue.value == '+65') {
    //验证新加坡手机
    if (SingaporePhone.test(phone.value)) {
    } else {
      showToast("新加坡手机号格式不正确！")
      return;
    }

  }
  const datas = await getVerification({ phone: phone.value });

  time.value = 60 * 1000;
  countDown.value?.reset();
  isWait.value = false;
  countDown?.value?.start();
};
const freeze = async (time: number) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time * 1000);
  });
};
const onSubmit = async (values: any) => {
  localStorage.clear();
  store.$state.userInfo = {};
  const datas: any = await userLogin(values);
  if (datas.code == '10000') {
    localStorage.setItem('userInfo', JSON.stringify(datas.data));
    // store.$state.userInfo = datas.data;
    store.$patch({
      userInfo: datas.data
    })
    showToast("登录成功！")
    //console.log(datas.data)
    //await freeze(2);
    //需要记录跳转到哪一个页面
    router.push('/');
  } else {
    return false;
  }

};
</script>
<style lang="less" scoped>
:root {
  --van-button-primary-background: #79C5EF;
}

:deep(.van-field__label) {
  width: 45px;
}

:deep(.van-icon-clear) {
  color: #ffffff !important;
}

#login {
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url(../assets/ui/img/login_bg.png);
  background-size: auto;
  background-repeat: round;
  overflow: hidden;

  .selfCity {
    width: 30px;
    border: none;
    background: none;
  }

  .login_title {
    font-family: PingFang SC, PingFang SC;
    font-weight: bolder;
    padding: 0 0 8px 0;
    font-size: 18px;
    color: rgba(40, 49, 76, 1);
    border-bottom: 4px solid rgba(32, 158, 228, 0.20);
  }

  .selfInput {
    background: #EAEFF2;
    margin-bottom: 20px;
    border-radius: 8px;
  }

  .tips {
    font-size: 14px;
    color: #AEBCC4;
    text-align: center;
  }

  .countDownTimes {
    font-weight: bold;
  }
}

.card {
  width: 350px;
  padding: 30px 0;
  border-radius: 20px;
  background: #fff;
  margin: 0 auto;
  display: flex;
  align-items: center;
  margin-top: 50rpx;
  justify-content: center;
}

.confirm-btn {
  width: 80%;
  margin: 0 auto;

  :deep(.van-button) {
    border-radius: 8px;
    background: #209EE4;
    border-radius: 10px 10px 10px 10px;
  }
}

input:-webkit-autofill,
textarea:-webkit-autofill,
select:-webkit-autofill {
  background-color: rgb(250, 255, 189);
  /* #FAFFBD; */
  background-image: none;
  color: rgb(0, 0, 0);
}
</style>
